/**
 * @description 把 16 进制的字符串转换成数组
 * @param {string} hexString 16进制的字符串
 * @returns {Array}
 */
export const strConvertToArr = (hexString: string) => {
  let arr = []
  for (let i = 0; i < hexString.length; i += 2) {
    arr.push(hexString.substring(i, i + 2))
  }
  // 去除起始码和结束码，去除校验和
  arr = arr.slice(3, arr.length - 2)
  return arr
}

/**
 * @description 把 16 进制的字符串转换成数组
 * @param {string} hexString 16进制的字符串
 * @returns {Array}
 */
export const hexToArr = (hexString: string) => {
  let arr = []
  for (let i = 0; i < hexString.length; i += 2) {
    arr.push(hexString.substring(i, i + 2))
  }
  return arr
}

/**
 * @description 校验校验和，将传尽量的数组的所有元素进行累加
 * @param {string} verifyArr
 * @returns {number} 16 进制的校验和
 * @rule 计算规则：校验和: 除了起始码与结束码外，其余的数据进行和校验（数据累加），如果超出一个字节，取低位（右）
 */
export const verifySum = (hexString: string | string[]) => {
  let hexArray
  if (typeof hexString === 'string') {
    hexArray = hexToArr(hexString)
  } else {
    hexArray = hexString
  }

  const dec = hexToDecimal(hexArray)
  // hexArray
  console.log(hexArray)
  const sum = dec.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
  let hexSum = numToHex(sum)

  if (hexSum.length > 2) {
    return hexSum.slice(-2)
  }
  return hexSum
}

/**
 * @description 把一组 16 进制转换为一组 10 进制
 * @param {Array} hex Array
 * @returns {Array} decimal Array
 */
export const hexToDecimal = (hexArray: Array<string>) => {
  return hexArray.map((hex: string) => parseInt(hex, 16))
}

/**
 * @description 获取数据长度
 * @param {string} hexString 16进制的字符串
 * @returns {string} 返回一个 16 进制1 个字节的数据长度. eg: '02'
 */
export const getDataLength = (hexString: string) => {
  const arr = hexToArr(hexString)

  const dataLen = arr.length.toString(16).padStart(2, '0')

  return dataLen
}

/**
 * @description 2进制转 16 进制，如果是一位，需要补位 0
 * @param {string} binary 2进制字符串 eg: '01111111'
 * @returns { string} 16进制
 */
export const binaryToHex = (binary: string) => {
  let decimal = parseInt(binary, 2)
  return decimal.toString(16).padStart(2, '0')
}

/**
 * @description 10进制转 16 进制，如果是一位，需要补位 0
 * @param {number|string} num 10进制的数字
 * @returns {string} 16进制
 */
export const numToHex = (num: string | number) => {
  const hex = Number(num).toString(16).padStart(2, '0')
  return hex
}

/**
 * @description 获取当前年月日周时分
 * @returns {object}
 */
export const getNowTime = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const week = date.getDay()
  const hour = date.getHours()
  const minute = date.getMinutes()

  return {
    year,
    month,
    day,
    week,
    hour,
    minute
  }
}
/**
 * @description 判读是否为空对象，如果是空，返回 true。
 * @param {object} obj 对象
 * @returns {boolean} 是否为空对象
 */
export const isNotEmptyObject = (obj: any) => {
  return Object.prototype.toString.call(obj) === '[object Object]' && obj.__proto__ === Object.prototype
}
